package com.t4.auth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.t4.auth.service.SysMenuService;
import com.t4.auth.service.SysUserService;
import com.t4.common.exception.T4Exception;
import com.t4.common.jwt.JwtHelper;
import com.t4.common.result.Result;
import com.t4.common.utils.MD5;
import com.t4.model.system.SysUser;
import com.t4.vo.system.LoginVo;
import com.t4.vo.system.RouterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMenuService sysMenuService;

    /**
     * 登录
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
        // 1. 获取输入用户名和密码
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        // 2. 根据用户查询数据库
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        // 3. 判断该用户是否存在
        if(StringUtils.isEmpty(sysUser)){
            throw new T4Exception(201, "用户不存在");
        }
        // 4. 判断密码是否正确（先对原密码进行加密，再比较）
        String password_input = MD5.encrypt(password);
        if(!password_input.equals(sysUser.getPassword())){
            throw new T4Exception(201, "密码不正确");
        }
        // 5. 判断用户是否禁用
        if(sysUser.getStatus().intValue() != 1){
            throw new T4Exception(201, "账号已禁用");
        }
        // 6. 根绝用户id和用户名生成token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", sysUser.getId());
        claims.put("username", sysUser.getUsername());
        String token = JwtHelper.createToken(claims);
        // 7. 返回数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }


    /**
     * 息获取用户信息，动态构建对应的菜单
     * @return
     */
    @ApiOperation(value = "息获取用户信息，动态构建对应的菜单")
    @GetMapping("/info")
    public Result info(HttpServletRequest request){
        // 1. 获取请求头中的token字符串
        String token = request.getHeader("token");
        // 2. 从token字符串中获取userId或username
        Long userId = JwtHelper.getClaim(token,"userId", Long.class);
        // 3. 根据userId查询数据库，把用户信息获取出来
        SysUser sysUser = sysUserService.getById(userId);
        // 4. 根据userId查询数据库，把用户可以操作的菜单列表获取出来（routers）
        List<RouterVo> routers = sysMenuService.findUserMenuListByUserId(userId);

        // 5. 根据userId查询数据库，把用户可以操作的按钮列表获取出来（button）
        List<String> button = sysMenuService.findUserPermsByUserId(userId);

        // 6. 返回数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("roles", "[admin]");
        map.put("name", sysUser.getName());
        map.put("introduction", sysUser.getDescription());
        map.put("avatar", "https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        map.put("routers", routers); // 返回用户可以操作的菜单
        map.put("button", button); // 返回用户可以操作的按钮
        return Result.success(map);
    }


    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){
        return Result.success();
    }

}
